#pragma once

#include<iostream>
#include<signal.h>

#include"TcpServer.hpp"
#include"Log.hpp"
#include"Task.hpp"
#include"ThreadPool.hpp"


const uint16_t PORT=8081;


class HttpServer
{
private:
    uint16_t port;
    TcpServer* tcp_svr;
    ThreadPool* thread_pool;
    bool stop;
public:
    HttpServer(uint16_t _port=PORT):port(_port),tcp_svr(nullptr),stop(false)
    {}

    void InitServer()
    {
        tcp_svr=TcpServer::GetInstance(port);
        thread_pool=ThreadPool::GetInstance();
        //忽略SIGPIPE信号，send时对端关闭，继续发送
        signal(SIGPIPE,SIG_IGN);
    }

    void Loop()
    {
        LOG(INFO,"Loop begin...");
        int listen_sock=tcp_svr->Sock();
        while(!stop)
        {
            struct sockaddr_in peer;
            socklen_t len=sizeof(peer);
            int sock=accept(listen_sock,(struct sockaddr*)&peer,&len);
            if(sock<0)
            {
                continue;
            }
            LOG(INFO,"Get a new link");
            Task task(sock);
            LOG(INFO,"creat task");
            thread_pool->PushTask(task);
        }
    }

    ~HttpServer()
    {}
};